<template>
  <el-row class="row">
    <ImportExcelModal :visible.sync="visible" fileType="chOutWarehouseTemp" title="导单"
                      downLoadUrl="/static/excel/出库暂存单导入模板.xlsx">
      <div slot="tips" class="col-xs-12 m--margin-top-10">
        <div class="alert alert-danger show text-center">
          由于上传文件转换为订单需要时间处理，上传后文件处理情况请在处理结果中查看，文件处理成功后订单将进入暂存单列表。
        </div>
      </div>
    </ImportExcelModal>

    <ImportResult :visible.sync="resultVisible"
                  url="/ms-common-excelupload/excel/getImportData?tempalateType=chOutWarehouseTemp"></ImportResult>

    <el-col :span="24">
      <Portlet title="出库暂存单">
        <el-form ref="searchForm" class="el-form-col el-form-s search-form" :model="search">
          <el-row :gutter="15" style="position:relative;">
            <el-col :span="4" style="position: absolute">
              <el-form-item prop="orderNo">
                <el-input v-model="search.orderNo" type="textarea" :rows="4"
                          placeholder="出库订单号  (支持多单查询，用英文逗号分隔)"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="4" :offset=4>
              <el-form-item prop="owner">
                <el-input v-model="search.owner" placeholder="商家名称"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item prop="warehouseId">
                <el-select v-model="search.warehouseId" filterable placeholder="出库仓">
                  <el-option v-for="item in warehouseIdArr"
                             :key="item.value"
                             :label="item.text"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="founderStartTime">
                <el-date-picker type="date"
                                placeholder="导入开始时间"
                                v-model="search.founderStartTime"
                                value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item prop="founderEndTime">
                <el-date-picker type="date"
                                placeholder="导入结束时间"
                                v-model="search.founderEndTime"
                                value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-row class="search-btns" :gutter="5">
                <el-col :span="12">
                  <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)"><span>搜索</span>
                  </el-button>
                </el-col>
                <!--<el-col :span="8">-->
                <!--<el-button type="primary" plain @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}</el-button>-->
                <!--</el-col>-->
                <el-col :span="12">
                  <el-button @click="resetFields" plain>重置</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row :gutter="15">
            <el-col :span="4" :offset=4>
              <el-form-item prop="founderUserName">
                <el-input v-model="search.founderUserName" placeholder="导入人"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </Portlet>
    </el-col>

    <el-col :span="24">
      <BasicTable
        ref="BasicTable"
        url="/ms-warehouse-order/outWarehose/findOutWarehouseListTemp"
        @selection-change="selectionChange"
        :columns="columns">
        <template slot="preColumn">
          <el-table-column prop="orderNo" v-if="tabIndex == 1" fixed="left" width="170px" align="center" label="出库订单号">
            <template slot-scope="scope">
              <a href="javascript: void (0);" @click.prevent="show(scope.row)">
                {{ scope.row.orderNo }}
              </a>
            </template>
          </el-table-column>
        </template>

        <template slot="column">
          <el-table-column fixed="right" align="center" width="100px" label="操作">
            <template v-if="tabIndex == 1" slot-scope="scope">
              <template>
                <el-button
                  size="mini"
                  type="text"
                  @click="show(scope.row)"
                >
                  详情
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="submit(scope.row)"
                >
                  提交
                </el-button>
              </template>

              <template v-if="tabIndex == 2">
                <a v-if="scope.row.errorFileId"
                   :href="urlPrefix + '/ms-mongodb/file/download?fileId=' + scope.row.errorFileId">错误文件下载</a>
              </template>
            </template>
          </el-table-column>
        </template>

        <template slot="buttons">
          <el-button type="primary" @click.prevent="visible = true">导入出库订单</el-button>
          <el-button type="primary" @click.prevent="resultVisible = true">导入結果</el-button>
          <el-button :loading="submitLoading" @click.prevent="submit()" type="warning">批量提交</el-button>
          <el-button @click.prevent="remove" type="danger">删除订单</el-button>
        </template>

        <span class="font-red" v-if="tabIndex == 2" slot="tips">
          由于上传文件转换为订单需要时间处理，上传后文件处理情况请在处理结果中查看，文件处理成功后订单将进入暂存单列表。
        </span>
      </BasicTable>
    </el-col>
  </el-row>
</template>
<script>

import ImportExcelModal from '@/views/oms/ImportExcelModal'
import ImportResult from '@/views/business/ImportResult'
import {copy, alert, dotData, confirm} from '@/utils'
import {urlPrefix} from '@/config/index'
import {decimalNumFilter, unixTimestampFilter, filterDataBaseDictionary} from '@/filters'
import {httpSuccessPost, getLoginUser} from '@/utils/ajax'
import StompJs from '@/utils/StompJs'
import {getAllWarehouse} from '@/utils/selectOptions'

export default {
  name: 'orderTempOut',
  components: {
    ImportExcelModal,
    ImportResult
  },
  filters: {
    decimalNumFilter,
    filterDataBaseDictionary
  },
  data() {
    return {
      tabIndex: 1,
      search: {
        orderNo: '',
        owner: '',
        warehouseId: '',
        founderStartTime: '',
        founderEndTime: '',
        founderUserName: ''
      },
      urlPrefix,
      customParams: {
        pageSize: 50,
        pageNum: 1
      },
      isOpen: false,
      columns: [
        {
          label: '出库仓',
          data: 'warehouse'
        },
        {
          label: '商家名称',
          data: 'cargoOwner'
        },
        {
          label: '总包件',
          data: 'totalPackage'
        },
        {
          label: '总体积',
          data: 'totalVolume'
        },
        {
          label: '总重量(kg)',
          data: 'totalWeight'
        },
        {
          label: '导入人',
          data: 'founderUserName'
        },
        {
          label: '导入时间',
          data: 'foundDate',
          render(data, full) {
            return unixTimestampFilter(data, 'YYYY-MM-DD HH:mm')
          }
        }
      ],
      visible: false,
      resultVisible: false,
      warehouseIdArr: [],
      rows: [],
      submitLoading: false,
      subOrderFinish: '',
      searchLoading: false
    }
  },
  created() {
    getAllWarehouse().then(arr => {
      this.warehouseIdArr = arr
    })
    let s1 = new StompJs()
    let userId = getLoginUser('id')
    s1.subscribe('/topic/' + userId + 'orderFinishOutWareshoue', (message) => {
      this.refresh()
    }).then(sub => {
      this.subOrderFinish = sub
    })
  },
  destroyed() {
    if (this.subOrderFinish) {
      this.subOrderFinish.unsubscribe()
    }
  },
  methods: {
    searchFunc(search) {
      const basicTable = this.$refs.BasicTable
      if (basicTable) {
        let params = copy(search)
        this.searchLoading = true
        basicTable.search(params).finally(_ => {
          this.searchLoading = false
        })
      }
    },
    show(data) {
      this.$router.push({path: '/ss-oms/order/temp-out-show/' + data.id})
    },
    selectionChange(rows) {
      this.rows = rows
    },
    submit(row) {
      let arr = []
      if (row === undefined) {
        arr = this.rows
      } else {
        arr = [row]
      }
      if (Array.isArray(arr) && arr.length > 0) {
        confirm(`
          <p>是否确认提交被选中的${arr.length}单出库暂存单？</p>
          <p>请确认出库暂存单信息正确，提交后您可以在出库单列表查看这些订单。</p>
        `, '提交出库订单', {
          type: 'warning',
          confirmButtonLoading: true,
          dangerouslyUseHTMLString: true,
          confirmCallBack: ({close, confirmButtonLoadingClose}) => {
            httpSuccessPost('/ms-warehouse-order/outWarehose/out-warehouse-place-order', {idList: arr.map(v => v.orderId)}).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                close().then(_ => {
                  confirm(`提交成功`, undefined, {
                    type: 'success'
                  }).finally(_ => {
                    this.refresh()
                  })
                  confirmButtonLoadingClose()
                })
              } else {
                confirmButtonLoadingClose()
              }
            }).catch(_ => {
              confirmButtonLoadingClose()
            })
          }
        })
      } else {
        alert('请选择数据')
      }
    },
    // reset 重置搜索框
    resetFields(searchForm) {
      this.$refs.searchForm.resetFields()
    },
    refresh() {
      this.searchFunc(this.search)
    },
    remove() {
      let data = this.rows
      if (Array.isArray(data) && data.length > 0) {
        confirm(`
          <p>是否确认移除被选中的${data.length}单出库暂存单？</p>
          <p>移除后不可恢复只能重新录单或导入。</p>
        `, '移除出库订单', {
          type: 'warning',
          confirmButtonLoading: true,
          dangerouslyUseHTMLString: true,
          confirmCallBack: ({close, confirmButtonLoadingClose}) => {
            httpSuccessPost('/ms-warehouse-order/outWarehose/out-warehouse-del-id', {idList: data.map(v => v.orderId)}).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                close().then(_ => {
                  confirm(`成功移除${data.length}单出库暂存单`, undefined, {
                    type: 'success'
                  }).finally(_ => {
                    this.refresh()
                  })
                  confirmButtonLoadingClose()
                })
              } else {
                confirmButtonLoadingClose()
              }
            }).catch(_ => {
              confirmButtonLoadingClose()
            })
          }
        })
      } else {
        alert('请选择数据')
      }
    }
  }
}
</script>
